﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public static class Solution9
    {
        public static int MyAtoi(string str)
        {
            char[] s = str.ToCharArray();
            if (str.Length == 0)
            {
                return 0;
            }

            int i = 0;
            while (i < str.Length)
            {
                if (str.Substring(i, 1) == " ")
                {
                    i++;
                    continue;
                }



                break;
            }
            if (i < str.Length)
            {
                if (s[i] != '-' && s[i] != '+' && s[i] < '0' && s[i] > '9')
                {
                    return 0;
                }
                int flag = 1;
                if (s[i] == '-')
                {
                    i++;
                    flag = -1;
                }
                else if (s[i] == '+')
                {
                    i++;
                }
                StringBuilder sb = new StringBuilder();
                int a = 0;
                while (i <= s.Length - 1)
                {
                    if ((s[i] >= '0' && s[i] <= '9'))
                    {
                        sb.Append(s[i]);
                        i++;
                        continue;
                    }
                    break;
                }
                double sum = 0;
                char[] ss = sb.ToString().ToCharArray();
                for (int j = 0; j < ss.Length; j++)
                {
                    int num = ss[j] - '0';
                    sum = sum * 10 + num;
                }
                if (flag * sum > int.MaxValue)
                {
                    return int.MaxValue;
                }
                if (flag * sum < int.MinValue)
                {
                    return int.MinValue;
                }
                return (int)sum * flag;
            }
            return 0;
        }
    }
}
